// hooks/useFetch.js
import { ref } from 'vue';

const Cache = new Map();

/**
 * 基础请求 Hook
 * @param {Function} fn - 请求函数
 * @param {Object} options - 配置选项
 * @param {*} options.initValue - 初始值
 * @param {string|Function} options.cache - 缓存配置
 * @param {Function} options.onSuccess - 成功回调
 */
function useFetch(fn, options = {}) {
  const isFetching = ref(false);
  const data = ref();
  const error = ref();

  // 设置初始值
  if (options.initValue !== undefined) {
    data.value = options.initValue;
  }

  function fetch(...args) {
    isFetching.value = true;
    let promise;

    if (options.cache) {
      const cacheKey = typeof options.cache === 'function' ? options.cache(...args) : options.cache || `${fn.name}_${args.join('_')}`;

      promise = Cache.get(cacheKey) || fn(...args);
      Cache.set(cacheKey, promise);
    } else {
      promise = fn(...args);
    }

    // 成功回调处理
    if (options.onSuccess) {
      promise = promise.then(options.onSuccess);
    }

    return promise
      .then(res => {
        data.value = res;
        isFetching.value = false;
        error.value = undefined;
        return res;
      })
      .catch(err => {
        isFetching.value = false;
        error.value = err;
        return Promise.reject(err);
      });
  }

  return {
    fetch,
    isFetching,
    data,
    error,
  };
}

export default useFetch;
